# 電報物件.
class Computer < ActiveRecord::Base
  
    # 一份電報清單可屬於多份最愛電報清單間.
  has_and_belongs_to_many :favorites
  
  # 一個電報能有多筆留言.
  has_many :posts, :dependent => :destroy #　刪除電報同時刪除留言.
  
  
  validates_presence_of :title, :cpu, :ram, :motherboard, 
    :vga, :hd, :cd, :audio, :power, :description, 
    :power_price, :user_name,  
    :message => '不能為空白'
  
  validates_numericality_of :cpu_price, :ram_price, 
    :motherboard_price, :vga_price, :hd_price,
    :cd_price, :audio_price, 
    :power_price, 
    :only_integer=>true, 
    :message => '不是數字'
  
  
  # 回傳最近幾個月的組裝報價.
  def self.find_all_computers(page, per_page, recent, order)
    paginate(:per_page => per_page, 
      :page => page,
      :conditions => ['created_at > ?', recent],
      :order => order)
  end
  
  # 回傳最近幾個月未滿此價格的組裝報價.
  def self.find_computers_less_than(price, page, per_page, recent, order)
    paginate(:per_page => per_page, 
      :page => page,
      :conditions => ['total_price < ? && created_at > ?', price, recent],
      :order => order)
  end
  
  # 回傳最近幾個月介於此價格區間的組裝報價.
  def self.find_computers_for_price(start_price, end_price, page, per_page, order)
    paginate(:per_page => per_page, 
      :page => page,
      :conditions => ["? <= total_price && total_price <= ?", start_price, end_price],
      :order => order)
  end
  
  # 回傳最近幾個月超過此價格的組裝報價.
  def self.find_computers_more_than(price, page, per_page, order)
#    find(:all, :conditions=>["total_price > ?", price])
    paginate(:per_page => per_page, 
      :page => page,
      :conditions => ["total_price > ?", price],
      :order => order)
  end
  
  
  protected
  
  # 在資料庫儲存前做驗證工作.
  def validate
    if cpu_price.nil? || cpu_price < 0
      errors.add(:cpu_price, '價格不能為空白或小於零')
    end
    if ram_price.nil? || ram_price < 0
      errors.add(:ram_price, '價格不能為空白或小於零')
    end
    if motherboard_price.nil? || motherboard_price < 0
      errors.add(:motherboard_price, '價格不能為空白或小於零')
    end
    if vga_price.nil? || vga_price < 0
      errors.add(:vga_price, '價格不能為空白或小於零')
    end
    if hd_price.nil? || hd_price < 0
      errors.add(:hd_price, '價格不能為空白或小於零')
    end
    if cd_price.nil? || cd_price < 0
      errors.add(:cd_price, '價格不能為空白或小於零')
    end
    if audio_price.nil? || audio_price < 0
      errors.add(:audio_price, '價格不能為空白或小於零')
    end
    if power_price.nil? || power_price < 0
      errors.add(:power_price, '價格不能為空白或小於零')
    end
  end
  
  # 在儲存前執行的動作.
  def before_save
    # 計算組裝電腦的總價.
    self.total_price = 
      self.cpu_price + 
      self.ram_price + 
      self.motherboard_price + 
      self.vga_price +
      self.hd_price + 
      self.cd_price + 
      self.audio_price + 
      self.power_price
  end
  
end
